import datetime
import os

import requests
from loguru import logger

import chenfeng_JXC
import chenfeng_SSKC
import main_bill
import main_product


def post_success():
    url = "http://1.95.41.135:8990/api/v1/mission/finish/RPA-JOB"
    res = requests.request("GET", url)
    logger.info(res.text)


def post_error(error_text):
    url = "http://1.95.41.135:8990/api/v1/mission/error/RPA-JOB"
    logger.info(error_text)
    res = requests.request("POST", url, json={"remark": error_text})
    logger.info(res.text)


def run_mission(host_url, command_text):
    success = True
    logger.info("进销存模块执行")
    success = chenfeng_JXC.main(host_url, command_text)
    if not success:
        post_error("进销存模块执行失败")
        return success
    if success:
        logger.info("实时库存模块执行")
        success = chenfeng_SSKC.main(host_url, command_text)
    if not success:
        post_error("实时库存模块执行失败")
        return success
    if success:
        logger.info("账单数据模块执行")
        success = main_bill.main(host_url, command_text)
    if not success:
        post_error("账单数据模块执行失败")
        return success
    if success:
        logger.info("商品数据模块执行")
        success = main_product.main(host_url, command_text)
    if not success:
        post_error("商品数据模块执行失败")
    return success


if __name__ == '__main__':
    # 记录日期的路经
    logger.add(os.path.join(os.getcwd(), 'logs', f'{datetime.datetime.now().strftime("%Y-%m-%d")}.txt'))
    host = "http://1.95.41.135:8990/api/v1"
    command = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe --window-size=1600,1024 --remote-debugging-port=9001"
    success = False
    try:
        logger.info("开始执行")
        success = run_mission(host, command)
        if success:
            logger.info("推送完成标志...")
            post_success()
    except:
        logger.exception("程序执行异常")
    finally:
        os.system('taskkill /F /IM chrome.exe')
